<template>
  <div class='container'>
    <el-card class="box-card">
      <!-- title -->
      <div slot="header" class="clearfix">
        <span>{{ id?'试题修改':'试题录入' }}</span>
      </div>
      <!-- title /-->
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <!-- 学科 -->
        <el-form-item label="学科: " prop="subjectID">
          <el-select
            v-model="form.subjectID"
            placeholder="请选择"
            style="width:400px;"
            @change="onSubjectChange"
          >
            <el-option
              v-for="item in subjectsSimpleList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <!-- 目录 -->
        <el-form-item label="目录: " prop="catalogID">
          <el-select v-model="form.catalogID" placeholder="请选择" style="width:400px;">
            <el-option
              v-for="item in directorysList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <!-- 企业 -->
        <el-form-item label="企业: " prop="enterpriseID">
          <el-select v-model="form.enterpriseID" placeholder="请选择" style="width:400px;">
            <el-option
              v-for="item in companyList"
              :key="item.value"
              :label="item.company"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <!-- 城市 -->
        <el-form-item label="城市: " prop="city">
          <city-picker :form="form" style="width:400px" />
        </el-form-item>
        <!-- 方向 -->
        <el-form-item label="方向: " prop="direction">
          <el-select v-model="form.direction" placeholder="请选择" style="width:400px;">
            <el-option
              v-for="item in directionList"
              :key="item"
              :label="item"
              :value="item"
            />
          </el-select>
        </el-form-item>
        <!-- 题型 -->
        <el-form-item label="题型: " prop="questionType">
          <el-radio-group v-model="form.questionType" @change="onQuestionsTypeChange">
            <el-radio
            v-for="item in questionTypeList"
            :key="item.value"
            :label="item.value"
            >
            {{ item.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <!-- 难度 -->
        <el-form-item label="难度: " prop="difficulty">
          <el-radio-group v-model="form.difficulty">
            <el-radio
            v-for="item in difficultyList"
            :key="item.value"
            :label="item.value"
            >
            {{ item.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <!-- 题干 -->
        <el-form-item label="题干: " prop="question">
          <quill-editor
            v-model="form.question"
            :options="editorOptions"
          />
        </el-form-item>
        <!-- 选项 -->
        <el-form-item label="选项: " v-if="!(form.questionType===3)">
          <div
          class="option_item"
          v-for="(item,index) in form.options"
          :key="item.code"
          style="margin:8px 0;"
          >
            <el-radio v-if="form.questionType===1" v-model="radio" :label="index">{{item.code}} :</el-radio>
            <el-checkbox v-else v-model="item.isRight" style="margin-right:30px;">{{item.code}} :</el-checkbox>
            <el-input style="width:240px;" v-model="item.title"/>
            <upload-image
            ref="uploadImage"
            :limit="1"
            :img="item.img"
            @on-success="onSuccess(item,$event)"
            @on-delete="onDelete(item)"
            style="margin-left:4px;"
            />
          </div>
          <el-button
          type="danger"
          size="mini"
          :disabled="form.questionType===1"
          @click="addOption"
          >+增加选项与答案</el-button>
        </el-form-item>
        <!-- 解析视频 -->
        <el-form-item label="解析视频: ">
          <el-input v-model="form.videoURL" style="width:400px;"/>
        </el-form-item>
        <!-- 答案解析 -->
        <el-form-item label="答案解析: " prop="answer">
          <quill-editor
            v-model="form.answer"
            :options="editorOptions"
          />
        </el-form-item>
        <!-- 题目备注 -->
        <el-form-item label="题目备注: ">
          <el-input type="textarea" v-model="form.remarks" style="width:400px;"/>
        </el-form-item>
        <!-- 试题标签 -->
        <el-form-item label="试题标签: ">
          <el-select
          v-model="form.tags"
          placeholder="请选择"
          style="width:400px;"
          multiple
          filterable
          allow-create
          default-first-option
          >
            <el-option
              v-for="item in tagsList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <!-- 提交/编辑按钮 -->
        <el-form-item>
            <el-button :type="id?'success':'primary'" @click="onConfirm">{{ id?'确认修改':'确认提交' }}</el-button>
        </el-form-item>
      </el-form>

    </el-card>
  </div>
</template>

<script>
import hljs from 'highlight.js'
import 'highlight.js/styles/monokai-sublime.css'
import {
  detail as getQuestionsDetail,
  add as addQuestion,
  update as updateQuestion
} from '@/api/hmmm/questions.js'
import { simple as subjectsSimple } from '@/api/hmmm/subjects.js'
import { list as getCompanyList } from '@/api/hmmm/companys.js'
import { simple as directorysSimple } from '@/api/hmmm/directorys.js'
import { simple as tagsSimple } from '@/api/hmmm/tags.js'
import { direction, questionType, difficulty } from '@/api/hmmm/constants.js'
import cityPicker from '../components/city-picker.vue'
export default {
  components: { cityPicker },
  name: 'questions-new',
  data () {
    return {
      questionsDetail: {}, // 修改页面的题库详情
      subjectsSimpleList: [], // 学科简单列表
      companyList: [], // 企业管理列表
      directionList: direction, // 方向
      questionTypeList: questionType, // 题型
      difficultyList: difficulty, // 难度
      directorysList: [], // 目录
      tagsList: [], // 标签
      radio: null,
      form: {
        subjectID: null, // 学科
        difficulty: 1, // 难度
        questionType: 1, // 题型
        enterpriseID: null, // 企业
        province: null, // 城市
        question: null, // 题干
        tags: null, // 试题标签
        city: null, // 地区
        remarks: null, // 题目备注
        direction: null, // 方向
        catalogID: null, // 目录
        videoURL: null, // 解析视频
        answer: null, // 答案解析
        options: [] // 选项
      },
      rules: {
        subjectID: [
          { required: true, message: '请选择学科', trigger: 'blur' }
        ],
        catalogID: [
          { required: true, message: '请选择目录', trigger: 'blur' }
        ],
        enterpriseID: [
          { required: true, message: '请选择企业', trigger: 'blur' }
        ],
        city: [
          { required: true, message: '请选择地区', trigger: 'blur' }
        ],
        direction: [
          { required: true, message: '请选择方向', trigger: 'blur' }
        ],
        questionType: [
          { required: true, message: '请选择题型', trigger: 'blur' }
        ],
        difficulty: [
          { required: true, message: '请选择难度', trigger: 'blur' }
        ],
        question: [
          { required: true, message: '请输入题干', trigger: 'blur' }
        ],
        answer: [
          { required: true, message: '请输入答案解析', trigger: 'blur' }
        ]
      },
      editorOptions: {
        placeholder: '',
        modules: {
          toolbar: [
            ['bold', 'italic', 'underline', 'strike'],
            [{ list: 'ordered' }, { list: 'bullet' }],
            ['blockquote'],
            ['code-block', 'image', 'link']
          ],
          // 语法高亮
          syntax: {
            highlight: (text) => hljs.highlightAuto(text).value
          }
        }
      }
    }
  },
  created () {
    if (this.id) this.loadQuestionsDetail()
    this.configOptions()
    this.loadSubjectsSimpleList()
    this.loadCompanyList()
  },
  watch: {
    radio (val) {
      this.form.options.forEach(item => (item.isRight = false))
      if (val === null) return
      this.form.options.find((item, index) => index === val).isRight = true
    }
  },
  computed: {
    id () {
      return this.$route.query.id
    }
  },
  methods: {
    // 配置选项的个数
    configOptions () {
      const codeList = [...Array(4).keys()].map(i => String.fromCharCode(i + 65))
      this.form.options = codeList.map(item => ({
        code: item, // 代码
        title: null, // 标题
        img: null, // 图片URL
        isRight: false // 是否正确答案
      }))
    },

    // 根据id加载题库详情
    async loadQuestionsDetail () {
      const { data } = await getQuestionsDetail({
        id: this.id
      })
      // 处理数据
      data.questionType = data.questionType - 0
      data.difficulty = data.difficulty - 0
      data.tags = data.tags.split(',')
      data.options.forEach(item => {
        item.isRight = !!item.isRight
      })
      if (data.questionType === 1) {
        this.radio = data.options.findIndex(item => item.isRight)
      }
      // 图片回显
      data.options.sort((a, b) => {
        if (a.code < b.code) {
          return -1
        }
      })
      console.log(data.options)
      console.log(this.$refs.uploadImage)
      data.options.forEach((item, index) => {
        item.img && this.$refs.uploadImage[index].fileList.push({
          uid: 11,
          url: data.options[index].img
        })
      })
      // 保存数据
      this.form = data
      // 加载学科和标签
      const { data: subData } = await directorysSimple({ subjectID: data.subjectID })
      this.directorysList = subData
      const { data: tagsData } = await tagsSimple({ subjectID: data.subjectID })
      this.tagsList = tagsData
    },

    // 加载学科简单列表
    async loadSubjectsSimpleList () {
      const { data } = await subjectsSimple()
      this.subjectsSimpleList = data
    },

    // 加载企业管理列表
    async loadCompanyList () {
      const { data } = await getCompanyList({
        pagesize: 10000
      })
      this.companyList = data.items
    },

    // 学科发生变化
    async onSubjectChange (val) {
      console.log('学科发生变化')
      this.form.catalogID = null
      this.form.tags = null
      const { data } = await directorysSimple({ subjectID: val })
      this.directorysList = data
      const { data: tagsData } = await tagsSimple({ subjectID: val })
      this.tagsList = tagsData
    },

    // 题型发生变化 重置options的isRight
    onQuestionsTypeChange () {
      this.form.options.forEach(item => (item.isRight = false))
      this.radio = null
    },

    // 确认提交/修改
    async onConfirm () {
      await this.$refs.form.validate()
      if (this.id) { // 修改题库
        console.log('修改')
        this.form.questionType = this.form.questionType + ''
        this.form.difficulty = this.form.difficulty + ''
        this.form.tags = this.form.tags && this.form.tags.join(',')
        await updateQuestion(this.form)
        this.$message.success('修改成功!')
        this.$router.push('/questions/list')
      } else { // 添加题库
        console.log('添加')
        // 处理数据
        this.form.questionType = this.form.questionType + ''
        this.form.difficulty = this.form.difficulty + ''
        this.form.tags = this.form.tags && this.form.tags.join(',')
        await addQuestion(this.form)
        this.$message.success('添加成功!')
        this.$router.push('/questions/list')
      }
    },

    // 添加选项
    addOption () {
      this.form.options.push({
        code: String.fromCharCode(this.form.options.length + 65), // 代码
        title: null, // 标题
        img: null, // 图片URL
        isRight: false // 是否正确答案
      })
    },

    // 上传图片成功
    onSuccess (item, fileList) {
      item.img = fileList[0].url
    },

    // 删除图片成功
    onDelete (item) {
      item.img = null
    }

  }
}
</script>

<style scoped lang='less'>
  .container {
    .box-card {
      margin: 20px;

      .quill-editor {
        height: 240px;
        padding-bottom: 60px;
      }

      .option_item {
        display: flex;
        align-items: center;
      }
    }
  }
</style>
